package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.mapper.DtsRoleMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DtsRoleServiceImpl implements DtsRoleService {
    @Autowired
    DtsRoleMapper roleMapper;

    @Autowired
    DtsAdminMapper adminMapper;

    @Autowired
    DtsPermissionMapper permissionMapper;

    /**
     * 通过id查找用户
     * @param roleIds
     * @return
     */
    @Override
    public Set<String> findRolesByIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        //条件查询
        wrapper.in(DtsRole::getId,roleIds);
        wrapper.eq(DtsRole::getDeleted,false);
        //通过条件查询全部记录
        List<DtsRole> roleList = roleMapper.selectList(wrapper);

        //lambda表达式
        //jdk8新特性
        //得到名字并封装成一个新的集合输出
        Set<String> roles = roleList.stream().map(role -> {
            return role.getName();
        }).collect(Collectors.toSet());
        return roles;
    }

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<DtsRole> findAll() {
        List<DtsRole> roleList = roleMapper.selectList(null);
        return roleList;
    }

    /**
     * 查找每页
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param rolename
     * @return
     */
    @Override
    public Map<String, Object> findByPage(Integer page, Integer limit, String sort, String order, String rolename) {
        IPage<DtsRole> iPage = new Page<>(page,limit);
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(rolename)){
            wrapper.eq("name",rolename);
        }

        if ("desc".equalsIgnoreCase(order)){
            wrapper.orderByDesc(sort);
        }else{
            wrapper.orderByAsc(sort);
        }

        roleMapper.selectPage(iPage, wrapper);

        //封装
        Map<String,Object> data = new HashMap<>();
        //每页条数
        data.put("total",iPage.getTotal());
        data.put("items",iPage.getRecords());

        return data;
    }

    @Override
    public void insert(DtsRole role) {
        role.setUpdateTime(new Date());
        role.setAddTime(new Date());
        role.setDeleted(false);

        roleMapper.insert(role);
    }

    @Override
    public void update(DtsRole role) {
        role.setUpdateTime(new Date());

        roleMapper.updateById(role);
    }

    /**
     * 1.判断该用户是否被管理员关联
     * 2.判断该用户是否被权限表关联
     * @param role
     */
    @Override
    public void delete(DtsRole role) {
        //是否被管理员关联
        LambdaQueryWrapper<DtsAdmin> adminWrapper = new LambdaQueryWrapper<>();
        adminWrapper.select(DtsAdmin::getRoleIds);
        List<DtsAdmin> adminList = adminMapper.selectList(adminWrapper);
        //遍历集合得到管理员id
        for (DtsAdmin admin : adminList) {
            Integer[] adminRoleIdsIds = admin.getRoleIds();
            //遍历集合将得到的用户id与管理员id比较，若相等则不能删除
            for (Integer adminRoleIdsId : adminRoleIdsIds) {
                if (adminRoleIdsId.equals(role.getId())){
                    throw  new RuntimeException("该用户被管理员关联，不能被删除！");
                }
            }
        }

        //是否被权限表关联
        LambdaQueryWrapper<DtsPermission> permissionWrapper = new LambdaQueryWrapper<>();
        permissionWrapper.eq(DtsPermission::getRoleId,role.getId());
        permissionWrapper.eq(DtsPermission::getDeleted,false);
        Integer count = permissionMapper.selectCount(permissionWrapper);

        if (count > 0) {
            throw new RuntimeException("该用户被权限表关联，不能删除！");
        }
    }

    /**
     * 判断是否为超级管理员
     * @param roleId
     * @return
     */
    @Override
    public boolean isSuperAdmin(Integer roleId) {
        DtsRole role = roleMapper.selectById(roleId);
        if (role.getName().equalsIgnoreCase("超级管理员")){
            return true;
        }
        return false;
    }
}
